<?php

namespace app\store\model;

use app\common\model\Gifts as GiftsModel;

/**
 * 爆品礼物模型
 * Class Gifts
 * @package app\store\model
 */
class Gifts extends GiftsModel
{
    /**
     * 添加商品
     * @param array $data
     * @return bool
     * @throws \think\exception\PDOException
     */
    public function add(array $data)
    {

        if (!$this->onValidate($data)) {
            return false;
        }
        if($data['gifts_type']==10){
            $data['gifts_price'] = 0;
            $data['gifts_distribution_price'] = 0;
        }
        $data['gifts_content'] = isset($data['gifts_content']) ? $data['gifts_content'] : '';
        $data['wxapp_id'] =  self::$wxapp_id;
        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time'] = strtotime($data['end_time']);

        // 开启事务
        $this->startTrans();
        try {
            // 添加商品
            $this->allowField(true)->save($data);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }



    /**
     * 编辑商品
     * @param $data
     * @return bool|mixed
     */
    public function edit($data)
    {

        if (!$this->onValidate($data)) {
            return false;
        }
        if($data['gifts_type']==10){
            $data['gifts_price'] = 0;
            $data['gifts_distribution_price'] = 0;
        }
        $data['gifts_content'] = isset($data['gifts_content']) ? $data['gifts_content'] : '';
        $data['wxapp_id'] =  self::$wxapp_id;
        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time'] = strtotime($data['end_time']);
        return $this->transaction(function () use ($data) {
            // 保存商品
            $this->allowField(true)->save($data);

            return true;
        });
    }

    /**
     * 表单验证
     * @param $data
     * @param string $scene
     * @return bool
     */
    private function onValidate($data)
    {

        if (empty($data['gifts_title'])) {
            $this->error = '请输入名称';
            return false;
        }

        if (empty($data['image_id'])) {
            $this->error = '请输入上传图片';
            return false;
        }
        if ($data['gifts_type']==20) {
            if($data['gifts_price']<=0){
                $this->error = '请输入现价';
                return false;
            }

        }

        if ($data['gifts_line_price']<=0) {
            $this->error = '请输入划线价';
            return false;
        }

        // 验证活动时间
        if (empty($data['start_time']) || empty($data['end_time'])) {
            $this->error = '请选择时间范围';
            return false;
        }
        // 验证活动时间
        if (empty($data['gifts_discription'])) {
            $this->error = '请输入简介';
            return false;
        }

        return true;
    }



    /**
     * 修改商品状态
     * @param $state
     * @return false|int
     */
    public function setStatus($state)
    {
        return $this->allowField(true)->save(['gifts_status' => $state ? 10 : 20]) !== false;
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->allowField(true)->save(['is_delete' => 1]);
    }




    /**
     * 订单导出
     * @param $dataType
     * @param $query
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function exportList($query)
    {

        header("Content-type:text/html;charset=utf-8");
        $mpName = '爆品推荐排名';
        $limit = 500;//每次只从数据库取50000条以防变量缓存太大
        // buffer计数器
        $cnt = 0;
        set_time_limit(0);
        //计算总的数据
        $sqlCount = $this->getExportList($query,0, $limit,true);

        if($sqlCount<1){
            $this->error = '无数据导出';
            return false;
        }

        $xlsTitle = [
            '排名', '用户ID', '昵称', '手机号', '爆品名称', '推荐次数'
        ];

        $fileName = $mpName . date('Y-m-d');// 文件名称可根据自己情况设定
        // 输出Excel文件头，可把user.csv换成你要的文件名
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');

        $fileNameArr = array();
        // 逐行取出数据，不浪费内存
        for ($i = 0; $i < ceil($sqlCount / $limit); $i++) {

            $fp = fopen($fileName . '_' . $i . '.csv', 'w'); //生成临时文件
            fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));// 转码 防止乱码(比如微信昵称)
            // chmod('attack_ip_info_' . $i . '.csv',777);//修改可执行权限
            $fileNameArr[] = $fileName . '_' . $i . '.csv'; // 将数据通过fputcsv写到文件句柄
            fputcsv($fp, $xlsTitle);
            $start = $i * $limit;
            $dataArr = $this->getExportList($query, $start, $limit,false);

            foreach ($dataArr as $a) {
                $cnt++;
                if ($limit == $cnt) {
                    //刷新一下输出buffer，防止由于数据过多造成问题
                    ob_flush();
                    flush();
                    $cnt = 0;
                }
                fputcsv($fp, $a);
            }
            fclose($fp);  //每生成一个文件关闭
        }

        //进行多个文件压缩
        $zip = new \ZipArchive();
        $filename = $fileName . ".zip";
        $zip->open($filename, $zip::CREATE);   //打开压缩包
        foreach ($fileNameArr as $file) {
            $zip->addFile($file, basename($file));   //向压缩包中添加文件
        }
        $zip->close();  //关闭压缩包
        foreach ($fileNameArr as $file) {
            unlink($file); //删除csv临时文件
        }

        //输出压缩文件提供下载
        header("Cache-Control: max-age=0");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . basename($filename)); // 文件名
        header("Content-Type: application/zip"); // zip格式的
        header("Content-Transfer-Encoding: binary"); //
        header('Content-Length: ' . filesize($filename)); //
        @readfile($filename);//输出文件;
        unlink($filename); //删除压缩包临时文件

    }



    /**
     * 打印订单列表
     * @param $dataType
     * @param array $query
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getExportList($query = [],$start, $limit,$count = false)
    {

        // 检索查询条件
        $params = array_merge([
            'search' => '',         // 搜索关键词
            'gifts_id' => $query['gifts_id']
        ], $query);

        // 筛选条件
        $filter = [];

        !empty($params['search']) && $filter['c.nickName|c.mobile'] = ['like', '%' . trim($params['search']) . '%'];

        if($count==true){
            // 获取数据列表
            $count = db('gifts_order')
                ->alias('a')
                ->join('yoshop_gifts_order_goods b','a.order_id=b.order_id')
                ->join('yoshop_user c','a.superior_user_id=c.user_id')
                ->where(['a.wxapp_id'=>self::$wxapp_id,'a.is_delete'=>0,'a.superior_user_id'=>['<>',0],'b.gifts_id'=>$params['gifts_id'],'a.pay_status'=>20])
                ->where($filter)
                ->group('a.superior_user_id')
                ->count();
            return $count;
        }

        // 获取数据列表
        $list = db('gifts_order')
            ->alias('a')
            ->join('yoshop_gifts_order_goods b','a.order_id=b.order_id')
            ->join('yoshop_user c','a.superior_user_id=c.user_id')
            ->where(['a.wxapp_id'=>self::$wxapp_id,'a.is_delete'=>0,'a.superior_user_id'=>['<>',0],'b.gifts_id'=>$params['gifts_id'],'a.pay_status'=>20])
            ->where($filter)
            ->group('a.superior_user_id')
            ->field([
                'count(a.superior_user_id)' => 'total',
                'a.superior_user_id' => 'superior_user_id',
                'c.user_id'=>'user_id',
                'c.nickName'=>'nickName',
                'c.avatarUrl'=>'avatarUrl',
                'b.gifts_title'=>'gifts_title',
                'c.mobile'=>'mobile',

            ])
            ->order('total desc')
            ->limit($start,$limit)
            ->select()->toArray();

        foreach ($list as $k=>&$v){
            $list[$k]['ID'] = $k+1;
        }


        $xlsTitle = [
            '排名', '用户ID', '昵称', '手机号', '爆品名称', '推荐次数'
        ];
        // 表格内容
        $dataArray = [];

        foreach ($list as $order) {
            $dataArray[] = [
                '排名' => $this->filterValue($order['ID']),
                '用户ID' => $this->filterValue($order['user_id']),
                '昵称' => $this->filterValue($order['nickName']),
                '手机号' => $this->filterValue($order['mobile']),
                '爆品名称' => $this->filterValue($order['gifts_title']),
                '推荐次数' => $this->filterValue($order['total']),
            ];

        }

        return  $dataArray;

    }

    /**
     * 表格值过滤
     * @param $value
     * @return string
     */
    private function filterValue($value)
    {
        return "\t" . $value . "\t";
    }

}
